# -*- coding:utf-8 -*-
'''
author:***y
time:2019-10-10
主要功能说明：
1、获取登录接口的token
2、动作推荐

'''
import requests
import csv
import json
import time

class Test_action_recommend():

    def __init__(self):
        print("-------------测试开始----------------")

    def login_token(self):
        # 初始化登录接口
        login_url = 'https://api.icarbonx.com/oauth2/token?grant_type=password&sms_verify=true'
        login_header = {"Authorization": "Basic Y29tLm1ldW0uY29hY2guaXBob25lOjdmYTYyZmFmYzgxZTgwMzY="}
        login_data = {
            "username": "15112345678",
            "password": "888888",
            "appName": "health-buddy",
            "grant_type": "password",
            "sms_verify": "true"
        }
        # 登录请求接口
        r_login = requests.post(url=login_url,data=login_data,headers=login_header)
        # 获取登录的响应报文
        token = r_login.json()['access_token']
        # print(token)
        '''请求接口获取token值'''
        return token

    def action_recommend(self):
        # 初始化
        action_flag_init = 0
        action_error_init = 0
        # 开始时间
        start = time.time()

        #读取csv文件，获取msg的入参
        with open('E:\\test\\HB\\action_recommend_init.csv','r') as ar:
            reader = csv.reader(ar)
            #从文本第二行开始读取
            # next(reader)
            for row in reader:
                print(row[0])
                #疾病食材问答接口的请求参数msg
                df_msg = {"msg":row[0]}
                print(df_msg)
                # 获取登录的token
                df_headers = {"Authorization": "Bearer " + self.login_token()}

                #运动动作推荐url
                df_url = 'https://api.icarbonx.com/ai/nlp/v1.0/action_recommend'
                #运动动作推荐请求接口
                r_df = requests.post(url=df_url,headers= df_headers,data=df_msg)
                #获取运动动作推荐的响应报文
                print(r_df)
                df_response = json.loads(r_df.text)
                print(df_response)
                print(type(df_response))

                #判断响应结果是否为空，则获取text的文本值
                if df_response:
                    print(df_response)
                    action_flag_init = action_flag_init + 1
                    print("动作推荐成功%d"%action_flag_init)
                    #获取响应结果中的bodypart和chineseName
                    action_response_all = df_response[0]
                    action_recommend_body = action_response_all['properties']['bodypart']
                    action_recommend_name = action_response_all['properties']['chineseName']
                    action_recommend_code = action_response_all['properties']['code']
                    # print(action_recommend_body)
                    # print(action_recommend_name)
                    # print(action_recommend_code)
                    # print(type(action_recommend_body))
                    # print(type(action_recommend_name))
                    # print(type(action_recommend_code))
                    #将int转换为str
                    action_recommend_code = str(action_recommend_code)
                    # print(type(action_recommend_code))



                    action_recommend = ['ac_msg','ac_name','ac_body','ac_code']

                    #保存响应结果到本地文件
                    with open('E:\\test\\HB\\action_recommend_success.csv', 'a+', encoding='utf-8-sig') as dof:
                        action_recommend[0] = row[0]
                        #将返回结果中的删除，避免换行
                        print(action_response_all)
                        # if '\n' in action_response_all:
                        #     action_response_all = action_response_all.replace("\n","")

                        action_recommend[1] = action_recommend_name
                        action_recommend[2] = action_recommend_body
                        action_recommend[3] = action_recommend_code
                        dof.write(','.join(action_recommend))
                        dof.write('\n')
                        dof.close()

                else:
                    action_error_init = action_error_init + 1
                    print("动作推荐结果为空，可能未识别到动作名称%d"%action_error_init)
                    with open('E:\\test\\HB\\action_recommend_fail.csv', 'a+', encoding='utf-8-sig') as doff:
                        action_recommend_fail = ['ac_msg']
                        action_recommend_fail[0] = row[0]
                        doff.write(','.join(action_recommend_fail))
                        doff.write('\n')
                        doff.close()
        ar.close()


        print("------动作推荐查询结果统计"+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())+"------")
        print("动作推荐成功%d" % action_flag_init)
        print("动作推荐无结果%d" % action_error_init)
        # 计算花费的时间
        print('cost time:{}'.format(time.time() - start))



if __name__ == '__main__':
    dac = Test_action_recommend()
    dac.action_recommend()










